package com.ashin.byteto;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;

import org.junit.After;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * https://blog.csdn.net/zhou_kapenter/article/details/62890262<br>
 * 解决Eclipse中无法直接使用Base64Encoder的问题 <br>
 * https://blog.csdn.net/u011514810/article/details/72725398
 * <p>
 * base64 实际是64进制
 * 
 * @author Ashin
 *
 */
@SuppressWarnings("restriction")
@FixMethodOrder(MethodSorters.JVM)
public class ByteToBase64 {

    private String hello = "hello base64";

    @After
    public void after() {
        System.out.println("--------------------");
    }

    /**
     * 早期的做法 性能差
     * 
     * @throws IOException
     */
    @Test
    public void test1Base64() throws IOException {
        System.out.println("test1Base64");

        BASE64Encoder encoder = new BASE64Encoder();
        BASE64Decoder decoder = new BASE64Decoder();

        // 编码
        String helloBase64 = encoder.encode(hello.getBytes("UTF-8"));
        System.out.println("base64编码:" + helloBase64);

        // 解码
        byte[] decodeBuffer = decoder.decodeBuffer(helloBase64);
        String helloDecoder = new String(decodeBuffer, "UTF-8");

        System.out.println("base64解码:" + helloDecoder);
    }

    /**
     * 比早期用sun.mis c套件还要更精简，效能实际执行起来也快了不少。缺点是需要引用Apache Commons Codec，很麻烦
     * 
     * @throws IOException
     */
    @Test
    public void test2Base64() throws IOException {
        System.out.println("test2Base64");
        org.apache.commons.codec.binary.Base64 base64 = new org.apache.commons.codec.binary.Base64();

        // 编码
        String encodedText = base64.encodeToString(hello.getBytes("UTF-8"));
        System.out.println(encodedText);

        // 解码
        System.out.println(new String(base64.decode(encodedText), "UTF-8"));

    }

    /**
     * jdk 1.8自带的方法性能好
     * 
     * @throws UnsupportedEncodingException
     */
    @Test
    public void test3Base64() throws UnsupportedEncodingException {
        System.out.println("test3Base64");

        Encoder encoder = Base64.getEncoder();
        Decoder decoder = Base64.getDecoder();

        // 编码
        String encodeToString = encoder.encodeToString(hello.getBytes("utf-8"));
        System.out.println(encodeToString);

        // 解码
        byte[] decode = decoder.decode(encodeToString);
        String helloDecorder = new String(decode, "utf-8");

        System.out.println(helloDecorder);
    }

}
